import { anyObj, enter, promisify, wxToast } from '../utils/util';
import config from './config';

export default async function request(
	{
		url = '',
		data,
		method = 'POST',
		header,
		timeout = config.timeout,
		baseUrl = config.baseUrl,
		errToast = false,
		contentTypeForm = false,
		query = {},
		showLoading,
	}:
		{
			baseUrl?: string;
			timeout?: number;
			url?: string;
			data?: object;
			header?: object;
			method?: "POST" | "OPTIONS" | "GET" | "HEAD" | "PUT" | "DELETE" | "TRACE" | "CONNECT";
			errToast?: Boolean;
			contentTypeForm?: Boolean;
			showLoading?: {
				title?: string;
				mask?: Boolean;
			},
			query?: anyObj;
			callback?: Function;
			filedCallback?: Function;
		}
): Promise<any> {
	if (url === '') return Promise.reject({ errorMsg: '请求失败' })
	if (showLoading) {
		wx.showLoading({
			title: showLoading.title || '',
			mask: Boolean('mask' in showLoading ? showLoading['mask'] : true)
		})
	}
	return new Promise((resolve, reject) => {
		const token = wx.getStorageSync('token');
		const openid = wx.getStorageSync('openid');
		const headerDefault: anyObj = {};

		if (!!token) {
			headerDefault.token = token;
		}
		if (!!openid) {
			headerDefault.openid = openid;
		}
		if (method === 'POST') {
			if (contentTypeForm) {
				headerDefault['content-type'] = 'application/x-www-form-urlencoded'
			} else {
				headerDefault['content-type'] = 'application/json'
			}
		}
		query = {
			...query,
			// CX_YHC_TYPE: "CUSTOMER_CLIENT_WX",  // 客户端类型
			// CX_YHS_ID: "CUSTOMER", // 登录客户端编码
			// CX_YHSS_ID: loginInfo.CX_YHSS_ID || '', // 登陆后返回的sessionId
			// CX_YHC_ID: loginInfo.CX_YHC_ID || '', // 登录后返回的clientId
			// CX_YHU_ID: loginInfo.CX_YHU_ID || '', // 登录后返回的用户Id
		}
		const queryArr: Array<string> = []
		for (const key in query) {
			let keyWidthType = key as any;
			queryArr.push(`${key}=${query[keyWidthType]}`)
		}
		wx.request({
			url: `${baseUrl}${url}${queryArr.length > 0 ? '?' : ''}${queryArr.join("&")}`,
			data,
			timeout,
			header: {
				...headerDefault,
				...header
			},
			method,
			success: async (response: any) => {
				const res = response.data

				if (res.code === 0 && res.succTips && typeof res.succTips === 'string') {
					wxToast({ title: res.succTips })
				}
				if (showLoading) {
					wx.hideLoading()
				}
				if (res.code != 0) {
					if (res.code == 5) {
						console.log("res: ", res)
						enter({
							url: '/pages/login/login'
						});
					}
					if (errToast) {
						let title = '请求失败'
						if (typeof res.errorMsg === 'string') {
							title = res.errorMsg
						} else if (typeof res.msg === 'string') {
							title = res.msg
						} else if (typeof res.error === 'string') {
							title = res.error
						}
						if (title) {
							wxToast({ title })
						}
					}
					return reject(res)
				}
				return resolve(res.data)
			},
			fail: async (err: any) => {
				console.warn("err: ", err)
				if (errToast) {
					let title = ''
					if (typeof err === 'string') {
						title = err
					}
					if (typeof err.errMsg === 'string') {
						title = err.errMsg
					}
					wxToast({ title })
				}
				if (showLoading) {
					wx.hideLoading()
				}
				reject(err)
			}
		})
	})
}

export const uploadImg = async (
	{
		count = 1,
		sourceType = ['album', 'camera'],
		limitSize = 1048576 * 10, // 限制文件大小，默认10M
	}:
		{
			count?: number,
			sourceType?: Array<'album' | 'camera'>,
			limitSize?: number
		}
): Promise<any> => {
	if (count > 10) count = 10
	try {
		const chooseMediaRes = await promisify(wx.chooseMedia, {
			count,
			sourceType
		})
		const imgUrl: Array<string> = []
		if (chooseMediaRes.tempFiles.length > 0) {
			wx.showLoading({ title: '正在上传' });
			for (let i = 0; i < chooseMediaRes.tempFiles.length; i++) {
				if (chooseMediaRes.tempFiles[i].size > limitSize) continue
				const response = await promisify(wx.uploadFile, {
					url: `${config.baseUrl}/user/file/upload?blocId=0&code=USER&public=true`,
					filePath: chooseMediaRes.tempFiles[i].tempFilePath,
					name: 'file',
					header: {
						"Content-Type": "multipart/form-data",
						"accept": 'application/json',
					},
					timeout: config.timeout,
				})
				const res = JSON.parse(response.data)
				// console.log("res: ", res)
				if (res.code != 0) {
					let title = '上传失败'
					if (res.msg && typeof res.msg === 'string') {
						title = res.msg
					}
					if (res.errorMsg && typeof res.errorMsg === 'string') {
						title = res.errorMsg
					}
					wxToast({ title })
				}
				if (res.data && res.data.url) {
					imgUrl.push(res.data.url)
				}
			}
			wx.hideLoading();
		}
		return Promise.resolve(imgUrl)
	} catch (error) {
		// console.log("error: ", error)
		return Promise.reject(error)
	}
};

/**
 * 小程序登录
 */
export const login = async () => {
	try {
		wx.showLoading({title: '正在登录...'});
		const { code } = await promisify(wx.login);
		console.log('code: ', code)
		const {token, openid, userInfo} = await request({
			url: '/api/customers/wechat/login',
			method: 'POST',
			contentTypeForm: true,
			data: {
				code
			},
			errToast: true,
		});
        const app = getApp();
        app.globalData.token = token;
        app.globalData.openid = openid;
        wx.setStorageSync("token", token);
        wx.setStorageSync("openid", openid);
        if (userInfo) {
            wx.setStorageSync("userInfo", JSON.stringify(userInfo));
            app.globalData.userInfo = userInfo;
        }
        return Promise.resolve({token, openid, userInfo});
	} catch (error) {
		console.warn('error: ', error)
		return Promise.reject(error);
	} finally {
		wx.hideLoading();
	}
}

export const verify = async () => {
	if (!wx.getStorageSync("token")) {
		enter({url: '/pages/login/login'});
	}
};